import 'dart:async';
import 'dart:math';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class Home3 extends StatefulWidget {
  const Home3({Key? key}) : super(key: key);

  @override
  _Home3State createState() => _Home3State();
}

class _Home3State extends State<Home3> with TickerProviderStateMixin {
  double percentage = 0.0;
  double newPercentage = 0.0;
  double arcAngle = pi;

  double dy = 0;
  double dx = 0;
  late ui.Image _localImage;

  @override
  void initState() {
    super.initState();
    setState(() {
      percentage = 0.0;
      arcAngle = 1 / 2 * pi;
    });
  }

  void updateArc(dx, dy, width) {
    double x = dx - width / 2;
    double y = dy - 210;

    double angel = atan2(y, x);
    if (angel < 0) {
      angel = 2 * pi + angel;
    }
    setState(() {
      arcAngle = angel + pi / 2;
    });
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final width = size.width;
    return new Scaffold(
        appBar: AppBar(
          title: Text('hello'),
        ),
        body: GestureDetector(
          onTapDown: (TapDownDetails details) {
            updateArc(
                details.globalPosition.dx, details.globalPosition.dy, width);
          },
          onLongPressMoveUpdate: (details) {
            updateArc(
                details.globalPosition.dx, details.globalPosition.dy, width);
          },
          onHorizontalDragUpdate: (details) {
            updateArc(
                details.globalPosition.dx, details.globalPosition.dy, width);
          },
          onVerticalDragUpdate: (details) {
            updateArc(
                details.globalPosition.dx, details.globalPosition.dy, width);
          },
          child: new Container(
            child: new Container(
              height: 200,
              width: double.infinity,
              child: new CustomPaint(
                foregroundPainter: new MyPainter(
                  lineColor: Colors.yellow,
                  completeColor: Colors.orange, //[Colors.orange,Colors.blue],
                  arcAngle: arcAngle,
                  width: 15.0,
                  // localImage: _localImage
                ),
                child: new Padding(
                  padding: const EdgeInsets.all(0),
                  child: new ElevatedButton(
                      child: new Text("Click"), onPressed: () {}),
                ),
              ),
            ),
          ),
        ));
  }
}

class MyPainter extends CustomPainter {
  Color lineColor;
  Color completeColor;
  double arcAngle;
  double width;
  late ui.Image _localImage;

  MyPainter({
    required this.lineColor,
    required this.completeColor,
    required this.arcAngle,
    required this.width,
    // ui.Image?localImage
  }) {
    // print(arcAngle.toString());
    // int i = 0;
    // i++;
  }

  @override
  void paint(Canvas canvas, Size size) {
    Paint line = Paint()
      ..color = lineColor
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.stroke
      ..strokeWidth = width + 8;

    Paint complete = Paint()
      // ..color = completeColor
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.stroke
      ..strokeWidth = width;

    Offset center = Offset(size.width / 2, size.height / 2); //  坐标中心
    double radius = min(size.width / 2, size.height / 2); //  半径


    

    canvas.drawCircle(center, radius, line);
    // print(arcAngle.toString());
    // if (arcAngle>2*pi){
    //   arcAngle -= 2*pi;
    // }
    double begin = -pi / 4;

    if (begin < 0 && arcAngle > 2 * pi + (pi / 2 + begin)) {
      arcAngle -= 2 * pi;
    }

    // print(arcAngle.toString());

    double end = arcAngle - pi / 2 - begin;
    // if (end<-pi/2){
    //   end = 2*pi+end;
    // }

    // double arcAngle = 2 * pi * (completePercent / 100);
    // print((arcAngle-pi/2).toString());
    // print('begin:'+begin.toString()+'   end:'+end.toString());

    // begin = 3*pi/2;
    // end = 7*pi/2;
    // Matrix4 matrix4 = Matrix4(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15)
    complete.shader =
        ui.Gradient.sweep(center,  [Colors.blue, Colors.red],[0,1],ui.TileMode.clamp,begin,end,null);

    // print('begin:'+begin.toString()+'  end:'+end.toString());
        // begin = 0;
    canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius),
        begin,
        end,
        // 2,
        // // -pi/2, //  从正上方开始
        // arcAngle-pi/2-2,
        false,
        complete);

    // if (localImage != null) {
    //   canvas.drawImage(localImage, Offset(10, 10), complete);
    // }

    // canvas.drawImage(
    //     Image.asset(
    //       "assets/images/caugh.png",
    //       fit: BoxFit.contain,
    //     ),
    //     Offset(10, 10),
    //     complete);
  }

  void setCanvasImageData(Canvas canvas) {}

  void drawImg() {
    var recorder = new ui.PictureRecorder();
    var origin = new ui.Offset(0, 0);
    // var canvas = new ui.Canvas(recorder,new Rect())
  }

  // ImageData getImageData(int sx,int sy,int sw,int sh){
  //   return convertNativeToDart_
  // }

  // Future<ui.Image> _loadImage(var path, bool isUrl) async {
  //   ImageStream stream;
  //   if (isUrl) {
  //     stream = NetworkImage(path).resolve(ImageConfiguration.empty);
  //   } else {
  //     stream = AssetImage(path, bundle: rootBundle)
  //         .resolve(ImageConfiguration.empty);
  //   }
  //   Completer<ui.Image> completer = Completer<ui.Image>();
  //   void listener(ImageInfo frame, bool synchronousCall) {
  //     final ui.Image image = frame.image;
  //     completer.complete(image);
  //     stream.removeListener(listener);
  //   }

  //   stream.addListener(listener);
  //   return completer.future;
  // }

  // Future<ui.Image> _loadImage(var path,bool isLocal) async{
  //    ImageStream stream;
  //    if (isLocal){
  //      stream = AssetImage(path,bundle: rootBundle).resolve(ImageConfiguration.empty);
  //    } else {
  //      stream = NetworkImage(path).resolve(ImageConfiguration.empty);
  //    }
  //    Completer<ui.Image> completer = Completer<ui.Image>();
  //    void listener(ImageInfo frame,bool synchronousCall){
  //      final ui.Image image = frame.image;
  //      completer.complete(image);
  //      stream.removeListener(listener);
  //    }
  //    stream.addListener(listener);
  //    return completer.future;
  // }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}
